import logging
import os
from logging import FileHandler, StreamHandler

import psutil


class CustomFormatter(logging.Formatter):
    def format(self, record):
        process = psutil.Process(os.getpid())
        record.cpu_percent = process.cpu_percent()
        record.memory_info = round(process.memory_info().rss / (1024 * 1024), 1)  # Convert to MB
        return super().format(record)


class SingletonLogger:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not isinstance(cls._instance, cls):
            cls._instance = super(SingletonLogger, cls).__new__(cls)
        return cls._instance

    def __init__(self, logger_name):
        self.logger = logging.getLogger(logger_name)
        self.logger.setLevel(logging.INFO)
        formatter = CustomFormatter(
            '[%(asctime)s] | %(levelname)s | CPU: %(cpu_percent)s | RAM: %(memory_info)s | %(message)s')

        # Handler for file
        fh = FileHandler('bot.log')
        fh.setFormatter(formatter)
        self.logger.addHandler(fh)

        # Handler for stdout
        ch = StreamHandler()
        ch.setFormatter(formatter)
        self.logger.addHandler(ch)

    @classmethod
    def get_instance(cls, logger_name):
        if not cls._instance:
            cls._instance = SingletonLogger(logger_name)
        return cls._instance

    def get_logger(self):
        return self.logger
